<template>
  <view style="position:relative;">
    <map
        id="myMap"
        style="width: 100%; height: 500rpx;"
        :latitude="data?.latitude || lat"
        :longitude="data?.longitude || lng"
        :markers="markers"
        :polyline="polyline"
        :show-location="true"
        :scale="scale"
        @tap="onMapTap"
        @markertap="onMarkerTap"
    />
    <!-- 悬浮按钮 -->
    <view class="fab" @tap="getLocation" v-if="location">
      <image src="/static/icon/common/position.png" style="width: 50rpx;height: 50rpx" mode="aspectFill"/>
    </view>
  </view>
</template>

<script setup lang="ts">
import {ref, defineProps, watch} from 'vue'
import {onLoad, onReady} from "@dcloudio/uni-app";

const props = defineProps(['data', 'location'])

const lat = ref(27.698709) // 默认北京天安门
const lng = ref(107.030059)
const markers = ref([])
const polyline = ref([])
const scale = ref(16)          // 初始缩放
const mapCtx = ref()

/* 获取当前位置 */
function getLocation() {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      lat.value = res.latitude
      lng.value = res.longitude
      markers.value = [{
        id: 0,
        latitude: res.latitude,
        longitude: res.longitude,
        iconPath: '/static/icon/common/location.png',
        width: 32,
        height: 32
      }]
      scale.value = 17
      mapCtx.value && mapCtx.value.moveToLocation({
        latitude: res.latitude,
        longitude: res.longitude,
        success: () => console.log('已移到当前位置'),
        fail: (err) => console.log("数据1", err)
      })
    },
    fail: (err) => {
      console.log("定位失败", err)
      uni.showToast({title: '定位失败', icon: 'none'})
    }
  })
}

watch(() => props.data, (newVal) => {
  if (newVal?.latitude && newVal.longitude) {
    markers.value = [{
      id: Date.now(),
      latitude: props.data.latitude,
      longitude: props.data.longitude,
      iconPath: '/static/icon/common/location.png',
      width: 30,
      height: 30
    }]
  }
}, {deep: true, immediate: true})

/* 点击地图打点 */
function onMapTap(e) {
  return
  // const {latitude, longitude} = e.detail
  markers.value.push({
    id: Date.now(),
    latitude: props.data.latitude,
    longitude: props.data.longitude,
    iconPath: '/static/icon/common/location.png',
    width: 30,
    height: 30
  })
}

/* 点击标记点 */
function onMarkerTap(e) {
  scale.value = 17
}

onReady(() => {
  // 注意：必须在 onReady 里创建，否则节点未挂载
  mapCtx.value = uni.createMapContext('myMap', this)
})

/* 页面加载就定位 */
// onLoad(() => getLocation())
</script>


<style scoped lang="scss">
.fab {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
}
</style>
